package com.safe.first.infrastructure.service;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @author Mickey
 * @since 2022/6/13
 **/
@Service
public class RoleService {

    public List<ConfigAttribute> roles = new ArrayList<>();
    private final Map<String, List<ConfigAttribute>> urlRoleMaps = new HashMap<>();

    @PostConstruct
    public void init() {
        // 初始化数据
        roles.addAll(SecurityConfig.createList("ROLE_USER", "ROLE_ADMIN", "ROLE_VIP"));
        urlRoleMaps.put("/", SecurityConfig.createList("ROLE_USER", "ROLE_ADMIN"));
        urlRoleMaps.put("/user/hello", SecurityConfig.createList("ROLE_USER", "ROLE_ADMIN", "ROLE_ANONYMOUS"));
        urlRoleMaps.put("/user/nickname", SecurityConfig.createList("ROLE_VIP"));
        urlRoleMaps.put("/admin/hello", SecurityConfig.createList("ROLE_ADMIN"));
        urlRoleMaps.put("/sms/code", SecurityConfig.createList("ROLE_ANONYMOUS"));
        urlRoleMaps.put("/actuator/health", SecurityConfig.createList("ROLE_ANONYMOUS"));
    }

    // 获取所有角色信息
    public Collection<ConfigAttribute> getAllRoles() {
        return Collections.unmodifiableList(roles);
    }
    // 依据请求路径查询所需权限
    public Collection<ConfigAttribute> getRoleByPath(String path) {
        Collection<ConfigAttribute> roles = urlRoleMaps.get(path);
        if (roles == null) {
            return Collections.EMPTY_LIST;
        }
        return Collections.unmodifiableCollection(roles);
    }

}
